import datetime

from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
# 显示所有标签列表
from django.views import View
from rest_framework.response import Response
from rest_framework.views import APIView
from apps.users.models import User
from apps.questions.models import Label, Reply, Question
from apps.questions.serializers.labels import LabelSerializer, QuestionSerializer,ReplySeriazlizer
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import UpdateModelMixin
class LableAPIView(APIView):
    def get(self,request):
        labels = Label.objects.all()
        serializer = LabelSerializer(labels,many=True)
        return Response(serializer.data)

    def post(self, request):
        data = request.data
        print(data)
        serializer = LabelSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors)
    def put(self,request,pk):
        user_id = request.user.id
        user = User.objects.get(id=user_id)
        label = Label.objects.get(id=pk)
        try:
            label.users.add(user)
            return Response({'success':True,'message':'关注成功'})
        except Exception:
            return Response({'success':False,'message':'关注失败'})

class LableFocusoutAPiView(APIView):
    def put(self,request,pk):
        user_id = request.user.id
        user = User.objects.get(id=user_id)
        label = Label.objects.get(id=pk)
        try:
            label.users.remove(user)
            return Response({'success': True, 'message': '取消关注成功'})
        except Exception:
            return Response({'success': False, 'message': '取消关注失败'})

# class LableListAPiView(APIView):
#     def get(self,request,pk):
#         user = User.objects.get(id=1)
#         label = user.labels.all()
#         serializer = LabelSerializer(instance=label,many=True)
#         return Response(serializer.data)
class LableListAPiView(APIView):
    def get(self,request,pk):
        label = Label.objects.get(id=pk)

        serializer = LabelSerializer(label)
        return Response(serializer.data)
class QuestionsAPIView(APIView):


    def post(self, request, *args, **kwargs):
        data = request.data
        serializer = QuestionSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors   )

    #一级视图
    #def post(self,request):

        # author_objs = Label.Author.objects.filter(label_id=3)
        # models.Book.objects.first().authors.add(*[1, 2])


        # #1.接收参数
        # book_dict = request.data
        # # 2.创建序列化器，并传递参数
        # serializer = QuestionSerializer(data=book_dict)
        # # 3.验证数据，并根据验证结果进行判断
        # if serializer.is_valid():
        #     # 4.数据验证没有问题，调用序列化器的save方法。来触发序列化器的create方法
        #     # create方法会调用模型来保存到数据库中
        #     serializer.save()
        #     # 5. 返回响应 serializer.data 就是字典数据
        #     return Response(serializer.data)
        # else:
        #     # 返回错误信息
        #     return Response({'msg': '保存失败'})
#查询最新回答问题
# class QuestionsnewAPIView(APIView):
#     def get(self,request,pk):
#         label=Label.objects.get(id=pk)
#         question=label.questions.all()
#         serializer = QuestionSerializer(instance=question,many=True)
#
#         return Response(serializer.data)
class QuestionsnewAPIView(APIView):
    def get(self,request,pk):
        a = []
        label=Label.objects.get(id=pk)
        question=label.questions.all().order_by('-replytime')
        info=question[0]
        a.append(info)

        serializer = QuestionSerializer(instance=a,many=True)

        return Response(serializer.data)
#查询用户关注标签
class SelectLableAPIView(APIView):
    def get(self,request):
        label_list = []
        user_obj = request.user
        label_names = user_obj.labels.all().values("label_name")
        label_ids = user_obj.labels.all().values("id")
        for eth in label_ids:
            label_list.append(eth)
        for ath in label_names:
            label_list.append(ath)

        return Response("查询结果：%s" % label_list)
# 回答问题
class ReplyAPIView(APIView):
    def post(self,request):
        data = request.data
        serializer = ReplySeriazlizer(data=data)
        if serializer.is_valid():
            serializer.save()
            today = datetime.now()
            question = Question.objects.get(id=data['problem'])
            question.reply += 1
            question.replytime = today
            question.save()
            return Response({'message':'发布成功','success':True})
        return Response({'message':'发布失败','success':False})
#回答有用
class ReplyUsefulAPIView(APIView):
    def put(self,request,pk):
        reply = Reply.objects.get(id=pk)
        try:
            reply.useful_count = reply.useful_count+1
            reply.save()
            return Response({'message':'回答有用+1','success':True})
        except Exception:
            return Response({'message':'点击失败','success':False})
#回答没用
class ReplyUnUsefulAPIView(APIView):
    def put(self,request,pk):
        reply = Reply.objects.get(id=pk)
        try:
            reply.unuseful_count = reply.unuseful_count+1
            reply.save()
            return Response({'message':'回答没用+1','success':True})
        except Exception:
            return Response({'message':'点击失败','success':False})

#查询最热回答问题
class QuestionshotAPIView(APIView):
    def get(self, request, pk):
        a=[]
        label = Label.objects.get(id=pk)
        question = label.questions.all().order_by('-reply')
        info=question[0]
        a.append(info)
        serializer = QuestionSerializer(instance=a, many=True)

        return Response(serializer.data)
#查询等待回答的问题
class QuestionswaitAPIView(APIView):
    def get(self, request, pk):
        label = Label.objects.get(id=pk)
        question = label.questions.filter(reply=0)
        print(question)
        serializer = QuestionSerializer(instance=question, many=True)

        return Response(serializer.data)

#查询问题详情
class QuestionslistAPIView(APIView):
    def get(self,request,pk):

        question=Question.objects.filter(id=pk)


        serializer = QuestionSerializer(instance=question,many=True)

        return Response(serializer.data)
#问题有用
class QuestionsUsefulAPIView(APIView):
    def put(self,request,id):
        question = Question.objects.get(id=id)
        try:
            question.useful_count+=1;
            question.save()
            return Response({'message': '问题有用+1', 'success': True})

        except Exception:
            return Response({'message': '点击失败', 'success': False})
#问题没用
class QuestionsUnUsefulAPIView(APIView):
    def put(self,request,id):
        question = Question.objects.get(id=id)
        try:
            question.unuseful_count+=1;
            question.save()
            return Response({'message': '问题无用+1', 'success': True})

        except Exception:
            return Response({'message': '点击失败', 'success': False})